package com.wutianyi.module.dao;

import java.util.List;

import com.wutianyi.module.commons.Item;
import com.wutianyi.module.commons.Pair;

public class ItemDaoMysqlImpl implements ItemDao {
	
	private ItemMapper itemMapper;
	private PropertiesMapper propertiesMapper;
	
	@Override
	public void insertItem(Item item) {
		itemMapper.insertItem(item);
		if (null != item.getProperties()) {
			int iId = item.getId();
			int order = 1;
			for (Pair pair : item.getProperties()) {
				propertiesMapper.insertProperty(iId, pair.getKey(), pair.getValue(), order);
				++order;
			}
		}
	}
	
	@Override
	public void insertItems(List<Item> items, int gId) {
		if (null == items || 0 == items.size()) {
			return;
		}
		for (Item item : items) {
			item.setgId(gId);
			insertItem(item);
		}
	}
	
	public ItemMapper getItemMapper() {
		return itemMapper;
	}
	
	public void setItemMapper(ItemMapper itemMapper) {
		this.itemMapper = itemMapper;
	}
	
	public PropertiesMapper getPropertiesMapper() {
		return propertiesMapper;
	}
	
	public void setPropertiesMapper(PropertiesMapper propertiesMapper) {
		this.propertiesMapper = propertiesMapper;
	}
	
	@Override
	public int updateItem(Item item) {
		int r = itemMapper.updateItem(item);
		
		if (r != 0) {
			if (null != item.getProperties()) {
				int iId = item.getId();
				for (Pair pair : item.getProperties()) {
					pair.setiId(iId);
					propertiesMapper.updateProperty(pair);
				}
			}
		}
		
		return r;
	}
	
	@Override
	public void updateItems(List<Item> items) {
		if (null == items || items.isEmpty()) {
			return;
		}
		for (Item item : items) {
			updateItem(item);
		}
	}
	
}
